package com.detection.dahua.service.impl;

import com.dahuatech.hutool.http.Method;
import com.dahuatech.hutool.json.JSONUtil;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import com.dahuatech.icc.oauth.model.v202010.OauthConfigUserPwdInfo;
import com.dahuatech.icc.oauth.utils.HttpUtils;
import com.detection.common.config.DetectionConfig;
import com.detection.common.domain.SysUser;
import com.detection.dahua.config.OauthConfigUtil;
import com.detection.dahua.model.accesscontrol.auth.PersonAuthRequest;
import com.detection.dahua.model.brm.person.PersonPageRequest;
import com.detection.dahua.model.brm.person.PersonPageResponse;
import com.detection.dahua.service.IDahuaUserService;
import com.detection.tcp.client.NettyTcpClient;
import com.detection.tcp.domain.TCPMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DahuaUserServiceImpl implements IDahuaUserService {

    /**
     * 获取全量人员信息
     * @return
     */
    public void getPersonList(){
        PersonPageRequest personPageRequest=new PersonPageRequest();
        personPageRequest.setPageNum(1);
        personPageRequest.setPageSize(50);
        List<Integer> statusList = new ArrayList<>();
        //获取状态为正常的人员
        statusList.add(1);
        personPageRequest.setStatusList(statusList);
        PersonPageResponse personPageResponse = getPersonPage(personPageRequest);
        if(personPageResponse.isSuccess()){
            if(!CollectionUtils.isEmpty(personPageResponse.getData().getPageData())) {
                Integer totalPages = personPageResponse.getData().getTotalPage();
                //若总页数大于0，遍历获取所有人员信息
                if (totalPages!=null&&totalPages>0) {
                    for (int i=0;i<totalPages;i++){
                        personPageRequest.setPageNum(i+1);
                        personPageResponse = getPersonPage(personPageRequest);
                        List<PersonPageResponse.PageVO.PersonInfoVO> pageData = personPageResponse.getData().getPageData();
                        for (PersonPageResponse.PageVO.PersonInfoVO personInfoVO : pageData) {
                            SysUser sysUser = new SysUser();
                            sysUser.setBirthday(personInfoVO.getBirthday());
                            sysUser.setEmail(personInfoVO.getEmail());
                            sysUser.setIdCardNo(personInfoVO.getPaperNumber());
                            sysUser.setPhonenumber(personInfoVO.getPhone());
                            sysUser.setCampCode(DetectionConfig.getCampCode());
                            sysUser.setOaId(String.valueOf(personInfoVO.getCode()));
                            sysUser.setUserName(personInfoVO.getName());
                            sysUser.setDeptId(personInfoVO.getDepartmentId());
                            sysUser.setDeptName(personInfoVO.getDepartmentName());
                            switch(personInfoVO.getSex()){
                                case "0":
                                    sysUser.setSex("2");
                                    break;
                                case "1":
                                    sysUser.setSex("0");
                                    break;
                                case "2":
                                    sysUser.setSex("1");
                                    break;
                            }
                            sendSysUser(sysUser);
                        }
                        //TODO: 进行数据存储工作或其他操作
                    }
                }
            }
        }
    }

    private void sendSysUser(SysUser sysUser) {
        TCPMessage tcpMessage = TCPMessage.builder()
                .flag("5")
                .data(sysUser)
                .campCode(DetectionConfig.getCampCode())
                .build();
        NettyTcpClient nettyTcpClient = new NettyTcpClient();
        nettyTcpClient.sendMessage(tcpMessage);
    }

    /**
     * 人员信息分页查询
     */
    public PersonPageResponse getPersonPage(PersonPageRequest personPageRequest){
        OauthConfigUserPwdInfo config = OauthConfigUtil.getOauthConfig();
        PersonPageResponse response=null;
        try {
            log.info("PersonDemo,getPersonPage,request:{}", JSONUtil.toJsonStr(personPageRequest));
            response = HttpUtils.executeJson("/evo-apigw/evo-brm/1.2.0/person/subsystem/page", personPageRequest,null, Method.POST , config, PersonPageResponse.class);
            log.info("PersonDemo,getPersonPage,response:{}", JSONUtil.toJsonStr(response));
        } catch (ClientException e) {
            log.error(e.getErrMsg(), e);
        }
        if(!response.isSuccess()) {
            log.info("人员信息分页查询失败:{}",response.getErrMsg());
        }
        return response;
    }

    /**
     * 门禁按人新增授权
     * @param personAuthRequest
     */
    public void personAuth(PersonAuthRequest personAuthRequest){
        OauthConfigUserPwdInfo config = OauthConfigUtil.getOauthConfig();
        GeneralResponse response=null;
        try {
            log.info("AuthDemo,personAuth,request:{}", JSONUtil.toJsonStr(personAuthRequest));
            response = HttpUtils.executeJson("/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/personAuthority/batchAuthority", personAuthRequest,null, Method.POST , config,GeneralResponse.class);
            log.info("AuthDemo,personAuth,response:{}", JSONUtil.toJsonStr(response));
        } catch (ClientException e) {
            log.error(e.getErrMsg(), e);
        }
        if(!response.isSuccess()) {
            log.info("按人新增授权失败:{}",response.getErrMsg());
        }
    }

    /**
     * 门禁按人新增授权
     * @param sysUser
     */
    public void personAuth(SysUser sysUser){
        String dahuaCode = sysUser.getOaId();
        PersonAuthRequest personAuthRequest = new PersonAuthRequest();
        List<String> list = new ArrayList<>();
        list.add(dahuaCode);
        personAuthRequest.setPersonCodes(list);
        personAuthRequest.setTimeQuantumId(1L);
        List<PersonAuthRequest.PrivilegeDetail> privilegeDetails = new ArrayList<>();
        PersonAuthRequest.PrivilegeDetail privilegeDetail = new PersonAuthRequest.PrivilegeDetail();
        privilegeDetail.setPrivilegeType(1);
//        todo 增加门禁点通道编号
//        privilegeDetail.setResourceCode();
        PersonAuthRequest.PrivilegeDetail privilegeDetail1 = new PersonAuthRequest.PrivilegeDetail();
        privilegeDetail1.setPrivilegeType(1);
//        privilegeDetail1.setResourceCode();
        privilegeDetails.add(privilegeDetail);
        privilegeDetails.add(privilegeDetail1);
        personAuthRequest.setPrivilegeDetails(privilegeDetails);
        personAuth(personAuthRequest);
    }

}
